

class API {
	constructor(config) {
	  this.baseURL = config.baseURL || ''
	}
	request(url, data = {}, method, headers = {}, isToLogin = false) {
		let headersObj = {
			"Content-Type": "application/json;",
			"authorization-bar": ""
		}
		// uni.getStorage({
		// 	key: 'authorizationBar',
		// 	success: function (res) {
		// 		console.log("----res-bar--")
		// 		console.log(res)
		// 		headersObj["authorization-bar"] = res.data
		// 	},
		// 	fail: (err) => {
		// 		console.log("----fail")
		// 		console.log(err)
		// 	}
		// })
		
		// headersObj["authorization-bar"] = getApp().globalData.authorizationBar
		try {
			const value = uni.getStorageSync('authorizationBar');
			if (value) {
				headersObj["authorization-bar"] = value
			}
		} catch (e) {
			// error
			console.log('获取本地缓存信息失败')
			console.log(e)
		}
		const value = uni.getStorageSync('storage_key');

		let config = Object.assign(headersObj, headers)
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.baseURL + url,
				method: method,
				data: data,
				header: headersObj,
				success(res) {
					if (res.data.code === "B000401" && isToLogin ) {
						let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
						let curRoute = routes[routes.length - 1].route 
						resolve(res.data)
						uni.navigateTo({
							url: '/pages/login/index?fromRoute=' + curRoute
						});
						return
					}  
					if (res.data.code === "B000401" && !isToLogin ) {
						reject(res.data)
						return
					}  
					resolve(res.data)
				},
				fail(error) {
					// console.log("---error-")
					// reject(error);
				},
				complete() {
					// console.log('--complete-')
				}
			})
		})
	}
	get(url, data, isToLogin){
		return this.request(url, data, 'GET', {}, isToLogin)
	}
	post(url, data, isToLogin){
		return this.request(url, data, 'POST', {}, isToLogin)
	}
}

export const amapAPI = new API({
  baseURL: getApp().globalData.envParam.baseURL,
})
